//
//  ChatRoomLSViewController.m
//  RongChatRoomDemo
// 横屏
//  Created by 杜立召 on 16/4/6.
//  Copyright © 2016年 rongcloud. All rights reserved.
//

#import "RCDLiveChatRoomLSViewController.h"
#import "RCDLiveMessageCell.h"
#import "RCDLiveTextMessageCell.h"
#import "RCDLiveGiftMessageCell.h"
#import "RCDLiveGiftMessage.h"
#import "RCDLiveMessageModel.h"
#import "RCDLive.h"
#import "RCDLiveCollectionViewHeader.h"
#import "RCDLiveKitUtility.h"
#import "RCDLiveKitCommonDefine.h"
#import <RongIMLib/RongIMLib.h>
#import <objc/runtime.h>
#import "MyLiveTipMessageCell.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "RCDLivePortraitViewCell.h"
#import "KSYLivePlaying.h"
#import "FMGVideoPlayView.h"

#import "UIView+RCDDanmaku.h"
#import "RCDDanmaku.h"
#import "RCDDanmakuManager.h"
#import <CommonCrypto/CommonDigest.h>
#import "ServiceUtils.h"
#import "ServiceNews.h"
#import "ShareService.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "UIControl+Blocks.h"
#import "UIView+XMGFrame.h"
#import "M_News.h"
#import "NewsOneOfImageCell.h"
#import "ZhuanTiCell.h"
#import "NewsAdvCell.h"
#import "NewsCell.h"
#import "NewsImageCell.h"
#import "WenBaTagListController.h"
#import "WenBaDetailController.h"
#import "NewsAlbumViewController.h"
#import "NewsWebViewController.h"
#import "SpecialNewsListViewController.h"
#import "NewsDetailViewController.h"
#import "NewsQuestionCell.h"


#import "NetworkUtils.h"
#import "HotWordViewController.h"
#import "HotWordService.h"



#define kRandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

//输入框的高度
#define MinHeight_InputView 50.0f
#define kBounds [UIScreen mainScreen].bounds.size
@interface RCDLiveChatRoomLSViewController () <
UICollectionViewDelegate, UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout, RCDLiveMessageCellDelegate, UIGestureRecognizerDelegate,
UIScrollViewDelegate, UINavigationControllerDelegate,RCTKInputBarControlDelegate,RCConnectionStatusChangeDelegate,UIAlertViewDelegate,UITableViewDataSource,UITableViewDelegate,NewsQuestionCellDelegate,MyPlayViewDelegate,MyWordViewDelegate>

@property(nonatomic, strong)RCDLiveCollectionViewHeader *collectionViewHeader;

/**
 *  存储长按返回的消息的model
 */
@property(nonatomic, strong) RCDLiveMessageModel *longPressSelectedModel;

/**
 *  是否需要滚动到底部
 */
@property(nonatomic, assign) BOOL isNeedScrollToButtom;


/**
 *  是否正在加载消息
 */
@property(nonatomic) BOOL isLoading;

/**
 *  会话名称
 */
@property(nonatomic,copy) NSString *navigationTitle;

/**
 *  点击空白区域事件
 */
@property(nonatomic, strong) UITapGestureRecognizer *resetBottomTapGesture;

/**
 *  金山视频播放器manager
 */
@property(nonatomic, strong) FMGVideoPlayView *livePlayingManager;

/**
 *  直播互动文字显示
 */
@property(nonatomic,strong) UIView *titleView ;

/**
 *  播放器view
 */
@property(nonatomic,strong) UIView *liveView;

/**
 *  底部显示未读消息view
 */
@property (nonatomic, strong) UIView *unreadButtonView;
@property(nonatomic, strong) UILabel *unReadNewMessageLabel;

/**
 *  滚动条不在底部的时候，接收到消息不滚动到底部，记录未读消息数
 */
@property (nonatomic, assign) NSInteger unreadNewMsgCount;

/**
 *  当前融云连接状态
 */
@property (nonatomic, assign) RCConnectionStatus currentConnectionStatus;



/**
 *  鲜花按钮
 */
@property(nonatomic,strong)UIButton *flowerBtn;

/**
 *  评论按钮
 */
@property(nonatomic,strong)UIButton *feedBackBtn;

/**
 *  掌声按钮
 */
@property(nonatomic,strong)UIButton *clapBtn;

@property(nonatomic,strong)UICollectionView *portraitsCollectionView;

@property(nonatomic,strong)NSMutableArray *userList;


@end

/**
 *  文本cell标示
 */
static NSString *const rctextCellIndentifier = @"rctextCellIndentifier";

/**
 *  小灰条提示cell标示
 */
static NSString *const RCDLiveTipMessageCellIndentifier = @"RCDLiveTipMessageCellIndentifier";

/**
 *  礼物cell标示
 */
static NSString *const RCDLiveGiftMessageCellIndentifier = @"RCDLiveGiftMessageCellIndentifier";

@implementation RCDLiveChatRoomLSViewController


- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self rcinit];
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil
               bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self rcinit];
    }
    return self;
}

- (void)rcinit {
    self.conversationDataRepository = [[NSMutableArray alloc] init];
    self.userList = [[NSMutableArray alloc] init];
    self.conversationMessageCollectionView = nil;
    [self registerNotification];
    self.defaultHistoryMessageCountOfChatRoom = 10;
    [[RCIMClient sharedRCIMClient]setRCConnectionStatusChangeDelegate:self];
}

/**
 *  注册监听Notification
 */
- (void)registerNotification {
    //注册接收消息
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveMessageNotification:)
     name:RCDLiveKitDispatchMessageNotification
     object:nil];
}

/**
 *  注册cell
 *
 *  @param cellClass  cell类型
 *  @param identifier cell标示
 */
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
    [self.conversationMessageCollectionView registerClass:cellClass
                               forCellWithReuseIdentifier:identifier];
}

/**
 *  页面加载
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.playHeight = self.view.bounds.size.height/3;
    self.titleHeight = 65;
    self.tabHeight = 44;
    
    self.navigationController.navigationBarHidden = YES;
    
    //默认进行弹幕缓存，不过量加载弹幕，如果想要同时大批量的显示弹幕，设置为yes，弹幕就不会做弹道检测和缓存
    RCDanmakuManager.isAllowOverLoad = NO;

    //初始化UI
    [self initializedSubViews];
    
    [self initChatroomTitle];
    
    
    __weak RCDLiveChatRoomLSViewController *weakSelf = self;
    
    @try {
        
        //聊天室类型进入时需要调用加入聊天室接口，退出时需要调用退出聊天室接口
        if (ConversationType_CHATROOM == self.conversationType) {
            [[RCIMClient sharedRCIMClient]
             joinChatRoom:self.targetId
             messageCount:self.defaultHistoryMessageCountOfChatRoom
             success:^{
                 dispatch_async(dispatch_get_main_queue(), ^{
                     [weakSelf initPlayView];
                     RCInformationNotificationMessage *joinChatroomMessage = [[RCInformationNotificationMessage alloc]init];
                     RCUserInfo *userinfo = [RCDLive sharedRCDLive].currentUserInfo;
                     joinChatroomMessage.message = [NSString stringWithFormat: @"%@ 加入了聊天室",userinfo.name];
                     [self sendMessage:joinChatroomMessage pushContent:nil];
                     [self refreshChatRoomMemberCount];//更新直播聊天室人数
                 });
             }
             error:^(RCErrorCode status) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     //TODO 版本不对？ 变量 KICKED_FROM_CHATROOM没有
                     if (status == FORBIDDEN_IN_GROUP) {
                         [weakSelf loadErrorAlert:NSLocalizedStringFromTable(@"JoinChatRoomRejected", @"RongCloudKit", nil)];
                     } else {
                         [weakSelf loadErrorAlert:NSLocalizedStringFromTable(@"JoinChatRoomFailed", @"RongCloudKit", nil)];
                     }
                 });
             }];
        }
        
    } @catch (NSException *exception) {
        NSLog(@"ChatRoomView-->viewDidLoad Exception: %@", exception);
    } @finally {
        
    }
    
    self.hotTJTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refreshData];
    }];
    
    self.hotTJTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.hotTJTableView.mj_header beginRefreshing];
    });
    NetworkStatus networkStatus = [NetworkUtils checkNetworkStatus];
        switch (networkStatus)
        {
            case NotReachable:        {
                break;
            }
            case ReachableViaWWAN:        {
                [self showHUDText:@"您不在WIFI环境下，建议在WIFI环境下观看视频"];
                break;
            }
            case ReachableViaWiFi:        {
                [self showHUDText:@"您在WIFI环境观看视频"];
                break;
            }
        }
}

-(void)initPlayView
{
    self.livePlayingManager =  [FMGVideoPlayView videoPlayView];
    [self.livePlayingManager initPlaying:self.contentURL];
    self.livePlayingManager.contrainerViewController = self;
    self.livePlayingManager.controlDelegate = self;
    [self initializedLiveSubViews];
    [self.livePlayingManager preparePlay];
//    [self.livePlayingManager startPlaying];
}


-(void)showHUDText:(NSString *)text
{
    MBProgressHUD *HUD;
    HUD = [[MBProgressHUD alloc] initWithView:[[UIApplication sharedApplication] keyWindow]];
    [[[UIApplication sharedApplication] keyWindow] addSubview:HUD];
    HUD.labelText = text;
    HUD.mode = MBProgressHUDModeText;
    
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
    //    HUD.yOffset = 150.0f;
    //    HUD.xOffset = 100.0f;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [HUD removeFromSuperview];
    }];
}

-(void)refreshChatRoomMemberCount {
    
    AFHTTPSessionManager *mgr = [ServiceUtils commonHTTPManager2];
    
    NSString *nonce = [NSString stringWithFormat:@"%d", rand()];
    //
    long timestamp = (long)[[NSDate date] timeIntervalSince1970];
    
    NSString *unionString = [NSString stringWithFormat:@"%@%@%ld", RONGCLOUD_IM_APPSECRET, nonce, timestamp];
    const char *cstr = [unionString cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:unionString.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    mgr.requestSerializer.HTTPShouldHandleCookies = YES;
    
    NSString *timestampStr = [NSString stringWithFormat:@"%ld", timestamp];
    [mgr.requestSerializer setValue:RONGCLOUD_IM_APPKEY forHTTPHeaderField:@"App-Key"];
    [mgr.requestSerializer setValue:nonce forHTTPHeaderField:@"Nonce"];
    [mgr.requestSerializer setValue:timestampStr forHTTPHeaderField:@"Timestamp"];
    [mgr.requestSerializer setValue:output forHTTPHeaderField:@"Signature"];
    
    __weak __typeof(&*self)weakSelf = self;
    
    // 2.拼接请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"chatroomId"] = _targetId;
    parameters[@"count"]=@"10";
    parameters[@"order"]=@"2";
    
    NSString *url = @"http://api.cn.ronghub.com/chatroom/user/query.json";
    
    [mgr POST:url parameters:parameters progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
          NSLog(@"OKOKOK");
          NSNumber *code = responseObject[@"code"];
          if (code.intValue == 200) {
              NSNumber *totals = responseObject[@"total"];
              NSLog(@"%@",totals);
              NSInteger randomTotals = [self randomUserCount:totals.intValue];
              [self.memberNumlabel setText:[NSString stringWithFormat:@"%@%ld人",@"观看人数：",randomTotals]];
              
          } else {
              dispatch_async(dispatch_get_main_queue(), ^{
                  [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
                  
              });
          }
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog( @"获取聊天室人数出错了,聊天室ID：%@",weakSelf.targetId);
          dispatch_async(dispatch_get_main_queue(), ^{
              [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
          });
          
      }];
    
}



-(NSInteger) randomUserCount:(NSInteger) totals
{
//    int x = arc4random() % 10;
//    if(totals<0) {
//        return totals*500+x;
//    }
//    return totals*200+x;
    return 21 + totals+39*totals;
}

- (void)sendDanmaku:(NSString *)text {
    if(true) {
        return;
    }
    if(!text || text.length == 0){
        return;
    }
    RCDDanmaku *danmaku = [[RCDDanmaku alloc]init];
    danmaku.contentStr = [[NSAttributedString alloc]initWithString:text attributes:@{NSForegroundColorAttributeName : kRandomColor}];
    [self.liveView sendDanmaku:danmaku];
}

- (void)sendCenterDanmaku:(NSString *)text {
    if(true) {
        return;
    }
    if(!text || text.length == 0){
        return;
    }
    RCDDanmaku *danmaku = [[RCDDanmaku alloc]init];
    danmaku.contentStr = [[NSAttributedString alloc]initWithString:text attributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:218.0/255 green:178.0/255 blue:115.0/255 alpha:1]}];
    danmaku.position = RCDDanmakuPositionCenterTop;
    [self.liveView sendDanmaku:danmaku];
}

/**
 *  加入聊天室失败的提示
 *
 *  @param title 提示内容
 */
- (void)loadErrorAlert:(NSString *)title {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)restoreFunc {
     [self.view addSubview:self.backBtn];
}

/**
 *讲视频控件重新添加到界面上
 */
-(void)restorePlay {
    if(self.livePlayingManager==nil || self.liveView==nil) {
        [self initPlayView];
        NSLog(@"restorePlay null------");
    }else {
        //重新计算高宽
        CGRect tmpR = self.liveView.frame;
        tmpR.size.height = self.playHeight;
        tmpR.size.width =self.titleContentView.frame.size.width;
        self.liveView.frame = tmpR;
        [self.view addSubview:self.liveView];
        [self.view addSubview:self.backBtn];
        NSLog(@"restorePlay not ------");
    }
 
}

/**
 *获取播放区的高度
 */
- (NSInteger)takePlayHeight{
    return self.playHeight;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view addGestureRecognizer:_resetBottomTapGesture];
    [self.conversationMessageCollectionView reloadData];
    if(self.livePlayingManager!=nil) {
        [self.livePlayingManager resumePlaying];
    }
    _backBtn.hidden = NO;
    [self.view bringSubviewToFront:self.backBtn];
    [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
    [self restorePlay];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationTitle = self.navigationItem.title;



}

/**
 *  移除监听
 *
 *  @param animated <#animated description#>
 */
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];

    //界面消失时，停止播放
    if( [self.livePlayingManager isPlaying] ) {
        [self.livePlayingManager pausePlaying];
    }
    
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:@"kRCPlayVoiceFinishNotification"
     object:nil];
    
    [self.conversationMessageCollectionView removeGestureRecognizer:_resetBottomTapGesture];
    [self.conversationMessageCollectionView
     addGestureRecognizer:_resetBottomTapGesture];
        
//    //退出页面，弹幕停止--横屏弹幕先取消
//    [self.view stopDanmaku];
    
}

/**
 *  回收的时候需要消耗播放器和退出聊天室
 */
- (void)dealloc {
    //    [self quitConversationViewAndClear];
}

/**
 *  点击返回的时候消耗播放器和退出聊天室
 *
 *  @param sender sender description
 */
- (void)ls_leftBarButtonItemPressed:(id)sender {
//    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:@"退出聊天室？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//    [alertview show];
    [self quitConversationViewAndClear];
}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    [self quitConversationViewAndClear];
//}

// 清理环境（退出聊天室并断开融云连接）
- (void)quitConversationViewAndClear {
    if (self.conversationType == ConversationType_CHATROOM) {
        @try {

        if (self.livePlayingManager) {
            if(self.livePlayingManager.isPlaying) {
                [self.livePlayingManager destroyPlaying];
            }
        }
        //退出聊天室
        [[RCIMClient sharedRCIMClient] quitChatRoom:self.targetId
                                            success:^{
                                                self.conversationMessageCollectionView.dataSource = nil;
                                                self.conversationMessageCollectionView.delegate = nil;
                                                [[NSNotificationCenter defaultCenter] removeObserver:self];
                                                
                                                //断开融云连接，如果你退出聊天室后还有融云的其他通讯功能操作，可以不用断开融云连接，否则断开连接后需要重新connectWithToken才能使用融云的功能
                                                @try {
                                                    [[RCDLive sharedRCDLive]logoutRongCloud];
                                                } @catch (NSException *exception) {
                                                } @finally {
                                                }
                                                
                                                
                                            } error:^(RCErrorCode status) {
                                                
                                            }];
            
            
        } @catch (NSException *exception) {
            
        } @finally {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }
}

- (void)initChatroomTitle{
    _titleContentView = [[UIView alloc] initWithFrame:CGRectMake(0, self.playHeight, self.view.bounds.size.width, self.titleHeight)];
    _titleContentView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    [self.view addSubview:_titleContentView];
    _titleContentView.alpha = 0.5;

    _chatroomlabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, self.view.bounds.size.width, 40)];
    _chatroomlabel.numberOfLines = 1;
    _chatroomlabel.font = [UIFont systemFontOfSize:24.f];
    _chatroomlabel.text = [NSString stringWithFormat:@"%@",_targetName];
    _chatroomlabel.textAlignment = NSTextAlignmentLeft;
    [_titleContentView addSubview:_chatroomlabel];
    
    _memberNumlabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 36, self.view.bounds.size.width, self.titleHeight-40)];
    _memberNumlabel.numberOfLines = 1;
    _memberNumlabel.font = [UIFont systemFontOfSize:12.f];
    _memberNumlabel.text = [NSString stringWithFormat:@"观看人数：%@",@"0"];
    _memberNumlabel.textAlignment = NSTextAlignmentLeft;
    [_titleContentView addSubview:_memberNumlabel];
    
    
    UIView *lineView = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [_titleContentView addSubview:lineView];
    
    
    
    [self.view sendSubviewToBack:_titleContentView];
    
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.minimumInteritemSpacing = 16;
//    layout.sectionInset = UIEdgeInsetsMake(0.0f, 20.0f, 0.0f, 20.0f);
//    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//    CGFloat memberHeadListViewY = _titleContentView.frame.origin.x + _titleContentView.frame.size.width;
//    self.portraitsCollectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(memberHeadListViewY,30,self.view.frame.size.width - memberHeadListViewY,35) collectionViewLayout:layout];
//    [self.view addSubview:self.portraitsCollectionView];
//    self.portraitsCollectionView.delegate = self;
//    self.portraitsCollectionView.dataSource = self;
//    self.portraitsCollectionView.backgroundColor = [UIColor clearColor];
//    
//    [self.portraitsCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//  
}

/**
 *  初始化页面控件
 */
- (void)initializedSubViews {
    [self setupTabTitleView ];
    
    //主显示区，显示
    if(self.mainView == nil){
        CGRect mainViewFrame = CGRectMake(0, self.playHeight+self.titleHeight+self.tabHeight+1, self.view.bounds.size.width,self.view.bounds.size.height-self.playHeight - self.titleHeight-self.tabHeight -50);
        self.mainView.backgroundColor =  [UIColor whiteColor];
        //RCDLive_RGBCOLOR(235, 235, 235);
        self.mainView = [[UIView alloc]initWithFrame:mainViewFrame];
        [self.view addSubview:self.mainView];
    }
    CGRect mainRect = self.mainView.frame;

    //详情区
    if(self.detailView == nil){
        CGRect contentViewFrame = CGRectMake(0, 0, self.view.bounds.size.width,mainRect.size.height);
        self.detailView.backgroundColor =  [UIColor whiteColor];
        //RCDLive_RGBCOLOR(235, 235, 235);
        self.detailView = [[UIView alloc]initWithFrame:contentViewFrame];
        self.detailView.hidden = YES;
        [self.mainView addSubview:self.detailView];
        
        CGRect textViewFrame = CGRectMake(10, 10, self.view.bounds.size.width-20,mainRect.size.height);
        self.detailTextView = [[UIWebView alloc]initWithFrame:textViewFrame];
        self.detailTextView.backgroundColor = [UIColor clearColor];
        [self.detailView addSubview:self.detailTextView];
        [self.detailTextView loadHTMLString:self.playDetail.f_content baseURL:nil];
        
    }
    //热门推荐区
    if(self.hotTJTableView == nil){
        CGRect contentViewFrame = CGRectMake(0, 0, self.view.bounds.size.width,mainRect.size.height);
        
        self.hotTJTableView = [[UITableView alloc] initWithFrame:contentViewFrame style:UITableViewStylePlain];
        self.hotTJTableView.delegate = self;
        self.hotTJTableView.dataSource = self;
        self.hotTJTableView.hidden=YES;
        self.hotTJTableView.tableFooterView = [UIView new];
        [self.mainView addSubview:self.hotTJTableView];

    }
    
    if(self.contentView == nil){
        CGRect contentViewFrame = CGRectMake(0, 0, self.view.bounds.size.width,mainRect.size.height);
        self.contentView.backgroundColor =  [UIColor whiteColor];
        //RCDLive_RGBCOLOR(235, 235, 235);
        self.contentView = [[UIView alloc]initWithFrame:contentViewFrame];
        [self.mainView addSubview:self.contentView];
    }
    
    //聊天消息区
    if (nil == self.conversationMessageCollectionView) {
        UICollectionViewFlowLayout *customFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        customFlowLayout.minimumLineSpacing = 0;
        customFlowLayout.sectionInset = UIEdgeInsetsMake(10.0f, 0.0f,5.0f, 0.0f);
        customFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        CGRect _conversationViewFrame = self.contentView.bounds;
        _conversationViewFrame.origin.y = 0;
        _conversationViewFrame.size.height = self.contentView.bounds.size.height;
        _conversationViewFrame.size.width = self.view.bounds.size.width;//240;//哦哦哦
        self.conversationMessageCollectionView =
        [[UICollectionView alloc] initWithFrame:_conversationViewFrame
                           collectionViewLayout:customFlowLayout];
        [self.conversationMessageCollectionView
         setBackgroundColor:[UIColor whiteColor]];
        self.conversationMessageCollectionView.alpha=0.7f;
        self.conversationMessageCollectionView.showsHorizontalScrollIndicator = NO;
        self.conversationMessageCollectionView.alwaysBounceVertical = YES;
        self.conversationMessageCollectionView.dataSource = self;
        self.conversationMessageCollectionView.delegate = self;
        [self.contentView addSubview:self.conversationMessageCollectionView];
    }
    //输入区
    if(self.inputBar == nil){
        float inputBarOriginY = self.conversationMessageCollectionView.bounds.size.height;
        float inputBarOriginX = self.conversationMessageCollectionView.frame.origin.x;
        float inputBarSizeWidth = self.contentView.frame.size.width;
        float inputBarSizeHeight = MinHeight_InputView;
        self.inputBar = [[RCDLiveInputBar alloc]initWithFrame:CGRectMake(inputBarOriginX, inputBarOriginY,inputBarSizeWidth,inputBarSizeHeight)];
        self.inputBar.delegate = self;
        self.inputBar.backgroundColor = [UIColor clearColor];
         self.inputBar.hidden = YES;//sah
        [self.view addSubview:self.inputBar];
    }
    self.collectionViewHeader = [[RCDLiveCollectionViewHeader alloc]
                                 initWithFrame:CGRectMake(0, -50, self.view.bounds.size.width, 40)];
    _collectionViewHeader.tag = 1999;
    [self.conversationMessageCollectionView addSubview:_collectionViewHeader];
    [self registerClass:[RCDLiveTextMessageCell class]forCellWithReuseIdentifier:rctextCellIndentifier];
    [self registerClass:[MyLiveTipMessageCell class]forCellWithReuseIdentifier:RCDLiveTipMessageCellIndentifier];
    [self registerClass:[RCDLiveGiftMessageCell class]forCellWithReuseIdentifier:RCDLiveGiftMessageCellIndentifier];
    
    [self.hotTJTableView registerNib:[UINib nibWithNibName:@"NewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsCell"];
    
    [self ls_changeModel:NO];
    _resetBottomTapGesture =[[UITapGestureRecognizer alloc]
                             initWithTarget:self
                             action:@selector(tap4ResetDefaultBottomBarStatus:)];
    [_resetBottomTapGesture setDelegate:self];
    
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _backBtn.frame = CGRectMake(10, 35, 72, 25);
    //button_back  back.png
    UIImageView *backImg = [[UIImageView alloc]
                            initWithImage:[UIImage imageNamed:@"mybuttonback"]];
    backImg.frame = CGRectMake(0, 0, 25, 25);
    [_backBtn addSubview:backImg];
    [_backBtn addTarget:self
                 action:@selector(ls_leftBarButtonItemPressed:)
       forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backBtn];

    __weak typeof(self) weak_self = self;

    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonShare.tintColor = [UIColor lightGrayColor];
    [buttonShare setImage:[UIImage imageNamed:@"btn_share"] forState:UIControlStateNormal];
    [buttonShare setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [buttonShare addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        NSString *shareUrl_ = weak_self.shareUrl;
        if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
        {
            shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
        }
        
        [ShareService share:weak_self url:shareUrl_ title:weak_self.targetName image:weak_self.shareImg completion:nil];
    }];
    
    
    UIView *bottomBarView = [UIView new];
    bottomBarView.backgroundColor = [UIColor colorWithRed:251/255.0f green:251/255.0f blue:251/255.0f alpha:1.0f];
    
    [self.view addSubview:bottomBarView];
    [bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(weak_self.view);
        make.height.equalTo(@44.0f);
    }];
    
    
    
    UIButton *buttonHotWord = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImageView *hotwordImg3 = [[UIImageView alloc]
                             initWithImage:[UIImage imageNamed:@"myhotword"]];
    hotwordImg3.frame = CGRectMake(0,0, 28, 28);
    [buttonHotWord addSubview:hotwordImg3];
    
    [buttonHotWord addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [HotWordService presentController:self delegate:self];
    }];
    
    UIButton *buttonWriteComment = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonWriteComment.layer.cornerRadius = 3.0f;
    buttonWriteComment.layer.masksToBounds = YES;
    buttonWriteComment.layer.borderWidth = .5f;
    buttonWriteComment.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [buttonWriteComment addTarget:self
                     action:@selector(showInputBar:)
           forControlEvents:UIControlEventTouchUpInside];

    
    _clapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //_clapBtn.frame = CGRectMake(self.view.frame.size.width-45, self.view.frame.size.height - 45, 35, 35);
    UIImageView *clapImg3 = [[UIImageView alloc]
                             initWithImage:[UIImage imageNamed:@"myheart"]];
    clapImg3.frame = CGRectMake(0,0, 28, 28);
    [_clapBtn addSubview:clapImg3];
    [_clapBtn addTarget:self
                 action:@selector(lsClapButtonPressed:)
       forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_clapBtn];
    

    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    
    [bottomBarView addSubview:linelab];
    
    
    [bottomBarView addSubview:buttonShare];
    [bottomBarView addSubview:buttonWriteComment];
    [bottomBarView addSubview:buttonHotWord];
    [bottomBarView addSubview:_clapBtn];
    
    [linelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(bottomBarView);
        make.height.equalTo(@0.5f);
    }];
    
    [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomBarView);
        make.left.equalTo(bottomBarView).with.offset(8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [buttonWriteComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(buttonShare.mas_right).offset(8.0f);
        make.right.mas_equalTo(buttonHotWord.mas_left).offset(-8.0f);
        make.top.equalTo(bottomBarView).offset(8.0f);
        make.bottom.equalTo(bottomBarView).offset(-8.0f);
        
    }];
    
    [_clapBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomBarView);
        make.right.equalTo(bottomBarView).with.offset(-8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];

    
    [buttonHotWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_clapBtn.mas_left).with.offset(-8.0f);
        make.left.mas_equalTo(buttonWriteComment.mas_right).with.offset(-8.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];

    
    
    
    

    //[self setupTest];
}

-(void)setupTest{
//    ChatRoomDetailViewController *detailVc=[[ChatRoomDetailViewController alloc]init];
//    detailVc.title = @"图文详情";
//    [self addChildViewController:detailVc];
//    
//    ChatRoomHotNewsViewController *newsVc=[[ChatRoomHotNewsViewController alloc]init];
//    newsVc.title = @"热门新闻";
//    [self addChildViewController:newsVc];
}

-(void)showInputBar:(id)sender{
   // [self.contentView bringSubviewToFront:self.inputBar];
    self.inputBar.hidden = NO;
    [self.inputBar setInputBarStatus:RCDLiveBottomBarKeyboardStatus];
}

/**
 *  发送鲜花
 *
 *  @param sender sender description
 */
-(void)flowerButtonPressed:(id)sender{
    RCDLiveGiftMessage *giftMessage = [[RCDLiveGiftMessage alloc]init];
    giftMessage.type = @"0";
    [self sendMessage:giftMessage pushContent:@""];
    NSString *text = [NSString stringWithFormat:@"%@ 送了一个钻戒",giftMessage.senderUserInfo.name];
    [self sendDanmaku:text];
}



/**
 *  发送掌声
 *
 *  @param sender <#sender description#>
 */
-(void)lsClapButtonPressed:(id)sender{
    RCDLiveGiftMessage *giftMessage = [[RCDLiveGiftMessage alloc]init];
    giftMessage.type = @"1";
    //sah 应客户要求，不需要显示点赞
//    [self sendMessage:giftMessage pushContent:@""];
//    NSString *text = [NSString stringWithFormat:@"%@ 为主播点了赞",giftMessage.senderUserInfo.name];
//    [self sendDanmaku:text];
    [self ls_praiseHeart];
}

/**
 *  未读消息View
 *
 *  @return <#return value description#>
 */
- (UIView *)unreadButtonView {
    if (!_unreadButtonView) {
        _unreadButtonView = [[UIView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 80)/2, self.view.frame.size.height - MinHeight_InputView - 30, 80, 30)];
        _unreadButtonView.userInteractionEnabled = YES;
        _unreadButtonView.backgroundColor = RCDLive_HEXCOLOR(0xffffff);
        _unreadButtonView.alpha = 0.7;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tabUnreadMsgCountIcon:)];
        [_unreadButtonView addGestureRecognizer:tap];
        _unreadButtonView.hidden = YES;
        [self.view addSubview:_unreadButtonView];
        _unreadButtonView.layer.cornerRadius = 4;
    }
    return _unreadButtonView;
}

/**
 *  底部新消息文字
 *
 *  @return return value description
 */
- (UILabel *)unReadNewMessageLabel {
    if (!_unReadNewMessageLabel) {
        _unReadNewMessageLabel = [[UILabel alloc]initWithFrame:_unreadButtonView.bounds];
        _unReadNewMessageLabel.backgroundColor = [UIColor clearColor];
        _unReadNewMessageLabel.font = [UIFont systemFontOfSize:12.0f];
        _unReadNewMessageLabel.textAlignment = NSTextAlignmentCenter;
        _unReadNewMessageLabel.textColor = RCDLive_HEXCOLOR(0xff4e00);
        [self.unreadButtonView addSubview:_unReadNewMessageLabel];
    }
    return _unReadNewMessageLabel;
    
}

/**
 *  更新底部新消息提示显示状态
 */
- (void)updateUnreadMsgCountLabel{
    if (self.unreadNewMsgCount == 0) {
        self.unreadButtonView.hidden = YES;
    }
    else{
        self.unreadButtonView.hidden = NO;
        self.unReadNewMessageLabel.text = @"底部有新消息";
    }
}

/**
 *  检查是否更新新消息提醒
 */
- (void) checkVisiableCell{
    NSIndexPath *lastPath = [self getLastIndexPathForVisibleItems];
    if (lastPath.row >= self.conversationDataRepository.count - self.unreadNewMsgCount || lastPath == nil || [self isAtTheBottomOfTableView] ) {
        self.unreadNewMsgCount = 0;
        [self updateUnreadMsgCountLabel];
    }
}

/**
 *  获取显示的最后一条消息的indexPath
 *
 *  @return indexPath
 */
- (NSIndexPath *)getLastIndexPathForVisibleItems
{
    NSArray *visiblePaths = [self.conversationMessageCollectionView indexPathsForVisibleItems];
    if (visiblePaths.count == 0) {
        return nil;
    }else if(visiblePaths.count == 1) {
        return (NSIndexPath *)[visiblePaths firstObject];
    }
    NSArray *sortedIndexPaths = [visiblePaths sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSIndexPath *path1 = (NSIndexPath *)obj1;
        NSIndexPath *path2 = (NSIndexPath *)obj2;
        return [path1 compare:path2];
    }];
    return (NSIndexPath *)[sortedIndexPaths lastObject];
}

/**
 *  点击未读提醒滚动到底部
 *
 *  @param gesture gesture description
 */
- (void)tabUnreadMsgCountIcon:(UIGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded) {
        [self scrollToBottomAnimated:YES];
    }
}
//-(NSUInteger)supportedInterfaceOrientations{
//    return UIInterfaceOrientationMaskLandscape;
//}

/**
 *  初始化视频直播
 */
- (void)initializedLiveSubViews {
    _liveView = self.livePlayingManager;
    _liveView.frame = CGRectMake(0, 0, self.view.bounds.size.width,self.playHeight);
    _liveView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_liveView];
    [self.view sendSubviewToBack:_liveView];
    
}

/**
 *  全屏和半屏模式切换
 *
 *  @param isFullScreen 全屏或者半屏
 */
- (void)ls_changeModel:(BOOL)isFullScreen {
//    self.livePlayingManager.currentLiveView.frame = self.view.frame;
    self.livePlayingManager.currentLiveView.frame =CGRectMake(0, 0, self.view.bounds.size.width,self.playHeight);
    _titleView.hidden = YES;
    
    self.conversationMessageCollectionView.backgroundColor = [UIColor clearColor];
    CGRect contentViewFrame = CGRectMake(0, 0, self.view.bounds.size.width,self.mainView.frame.size.height);
    self.contentView.frame = contentViewFrame;
    
    [self.view sendSubviewToBack:_liveView];
    
    float inputBarOriginY = self.conversationMessageCollectionView.bounds.size.height;
    float inputBarOriginX = self.conversationMessageCollectionView.frame.origin.x;
    float inputBarSizeWidth = self.contentView.frame.size.width;
    float inputBarSizeHeight = MinHeight_InputView;
    //添加输入框
    [self.inputBar changeInputBarFrame:CGRectMake(inputBarOriginX, inputBarOriginY,inputBarSizeWidth,inputBarSizeHeight)];
    [self.conversationMessageCollectionView reloadData];
    [self.unreadButtonView setFrame:CGRectMake((self.view.frame.size.width - 80)/2, self.view.frame.size.height - MinHeight_InputView - 30, 80, 30)];
}

/**
 *  顶部插入历史消息
 *
 *  @param model 消息Model
 */
- (void)pushOldMessageModel:(RCDLiveMessageModel *)model {
    if (!(!model.content && model.messageId > 0)
        && !([[model.content class] persistentFlag] & MessagePersistent_ISPERSISTED)) {
        return;
    }
    long ne_wId = model.messageId;
    for (RCDLiveMessageModel *__item in self.conversationDataRepository) {
        if (ne_wId == __item.messageId) {
            return;
        }
    }
    [self.conversationDataRepository insertObject:model atIndex:0];
}

/**
 *  加载历史消息(暂时没有保存聊天室消息)
 */
- (void)loadMoreHistoryMessage {
    long lastMessageId = -1;
    if (self.conversationDataRepository.count > 0) {
        RCDLiveMessageModel *model = [self.conversationDataRepository objectAtIndex:0];
        lastMessageId = model.messageId;
    }
    
    NSArray *__messageArray =
    [[RCIMClient sharedRCIMClient] getHistoryMessages:_conversationType
                                             targetId:_targetId
                                      oldestMessageId:lastMessageId
                                                count:10];
    for (int i = 0; i < __messageArray.count; i++) {
        RCMessage *rcMsg = [__messageArray objectAtIndex:i];
        RCDLiveMessageModel *model = [[RCDLiveMessageModel alloc] initWithMessage:rcMsg];
        [self pushOldMessageModel:model];
    }
    [self.conversationMessageCollectionView reloadData];
    if (_conversationDataRepository != nil &&
        _conversationDataRepository.count > 0 &&
        [self.conversationMessageCollectionView numberOfItemsInSection:0] >=
        __messageArray.count - 1) {
        NSIndexPath *indexPath =
        [NSIndexPath indexPathForRow:__messageArray.count - 1 inSection:0];
        [self.conversationMessageCollectionView scrollToItemAtIndexPath:indexPath
                                                       atScrollPosition:UICollectionViewScrollPositionTop
                                                               animated:NO];
    }
}


#pragma mark <UIScrollViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
}

/**
 *  滚动条滚动时显示正在加载loading
 *
 *  @param scrollView
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 是否显示右下未读icon
    if (self.unreadNewMsgCount != 0) {
        [self checkVisiableCell];
    }
    
    if (scrollView.contentOffset.y < -5.0f) {
        [self.collectionViewHeader startAnimating];
    } else {
        [self.collectionViewHeader stopAnimating];
        _isLoading = NO;
    }
}

/**
 *  滚动结束加载消息 （聊天室消息还没存储，所以暂时还没有此功能）
 *
 *  @param scrollView scrollView description
 *  @param decelerate decelerate description
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
                  willDecelerate:(BOOL)decelerate {
    if (scrollView.contentOffset.y < -15.0f && !_isLoading) {
        _isLoading = YES;
    }
}

/**
 *  消息滚动到底部
 *
 *  @param animated 是否开启动画效果
 */
- (void)scrollToBottomAnimated:(BOOL)animated {
    if ([self.conversationMessageCollectionView numberOfSections] == 0) {
        return;
    }
    NSUInteger finalRow = MAX(0, [self.conversationMessageCollectionView numberOfItemsInSection:0] - 1);
    if (0 == finalRow) {
        return;
    }
    NSIndexPath *finalIndexPath =
    [NSIndexPath indexPathForItem:finalRow inSection:0];
    [self.conversationMessageCollectionView scrollToItemAtIndexPath:finalIndexPath
                                                   atScrollPosition:UICollectionViewScrollPositionTop
                                                           animated:animated];
}

#pragma mark <UICollectionViewDataSource>
/**
 *  定义展示的UICollectionViewCell的个数
 *
 *  @return
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    if ([collectionView isEqual:self.portraitsCollectionView]) {
        return self.userList.count;
    }
    return self.conversationDataRepository.count;
}

/**
 *  每个UICollectionView展示的内容
 *
 *  @return
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.portraitsCollectionView]) {
        RCDLivePortraitViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"portraitcell" forIndexPath:indexPath];
        RCUserInfo *user = self.userList[indexPath.row];
        NSString *str = user.portraitUri;
        cell.portaitView.image = [UIImage imageNamed:str];
        return cell;
    }
    //NSLog(@"path row is %d", indexPath.row);
    RCDLiveMessageModel *model =
    [self.conversationDataRepository objectAtIndex:indexPath.row];
    RCMessageContent *messageContent = model.content;
    RCDLiveMessageBaseCell *cell = nil;
    if ([messageContent isMemberOfClass:[RCInformationNotificationMessage class]] || [messageContent isMemberOfClass:[RCTextMessage class]] || [messageContent isMemberOfClass:[RCDLiveGiftMessage class]]){
        MyLiveTipMessageCell *__cell = [collectionView dequeueReusableCellWithReuseIdentifier:RCDLiveTipMessageCellIndentifier forIndexPath:indexPath];
        __cell.isFullScreenMode = YES;
        __cell.isLandScape = YES;
        [__cell setDataModel:model];
        [__cell setDelegate:self];
        cell = __cell;
    }
    
    return cell;
}

#pragma mark <UICollectionViewDelegateFlowLayout>

/**
 *  cell的大小
 *
 *  @return
 */
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.portraitsCollectionView]) {
        return CGSizeMake(35,35);
    }
    RCDLiveMessageModel *model =
    [self.conversationDataRepository objectAtIndex:indexPath.row];
    if (model.cellSize.height > 0) {
        return model.cellSize;
    }
    RCMessageContent *messageContent = model.content;
    if ([messageContent isMemberOfClass:[RCTextMessage class]] || [messageContent isMemberOfClass:[RCInformationNotificationMessage class]] || [messageContent isMemberOfClass:[RCDLiveGiftMessage class]]) {
        model.cellSize = [self sizeForItem:collectionView atIndexPath:indexPath];
    } else {
        return CGSizeZero;
    }
    return model.cellSize;
}

/**
 *  计算不同消息的具体尺寸
 *
 *  @return
 */
- (CGSize)sizeForItem:(UICollectionView *)collectionView
          atIndexPath:(NSIndexPath *)indexPath {
    CGFloat __width = CGRectGetWidth(collectionView.frame);
    RCDLiveMessageModel *model =
    [self.conversationDataRepository objectAtIndex:indexPath.row];
    RCMessageContent *messageContent = model.content;
    CGFloat __height = 0.0f;
    NSString *localizedMessage;
    if ([messageContent isMemberOfClass:[RCInformationNotificationMessage class]]) {
        RCInformationNotificationMessage *notification = (RCInformationNotificationMessage *)messageContent;
        localizedMessage = [RCDLiveKitUtility formatMessage:notification];
        NSString *name;
        if (messageContent.senderUserInfo) {
            name = messageContent.senderUserInfo.name;
        }
        localizedMessage = [NSString stringWithFormat:@"%@\n %@\n",name,localizedMessage];
    }else if ([messageContent isMemberOfClass:[RCTextMessage class]]){
        RCTextMessage *notification = (RCTextMessage *)messageContent;
        localizedMessage = [RCDLiveKitUtility formatMessage:notification];
        NSString *name;
        if (messageContent.senderUserInfo) {
            name = messageContent.senderUserInfo.name;
        }
        localizedMessage = [NSString stringWithFormat:@"%@\n %@\n",name,localizedMessage];
    }else if ([messageContent isMemberOfClass:[RCDLiveGiftMessage class]]){
        RCDLiveGiftMessage *notification = (RCDLiveGiftMessage *)messageContent;
        localizedMessage = @"送了一个钻戒";
        if(notification && [notification.type isEqualToString:@"1"]){
            localizedMessage = @"为主播点了赞";
        }
        
        NSString *name;
        if (messageContent.senderUserInfo) {
            name = messageContent.senderUserInfo.name;
        }
        //昵称+时间 一行 ，消息内容一行
        localizedMessage = [NSString stringWithFormat:@"%@\n %@\n",name,localizedMessage];
    }
    
    
    CGSize __labelSize = [MyLiveTipMessageCell getTipMessageCellSize:localizedMessage];
    __height = __height + __labelSize.height;
    
    return CGSizeMake(__width, __height);
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

#pragma mark <UICollectionViewDelegate>

/**
 *   UICollectionView被选中时调用的方法
 *
 *  @return
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"selectview");
}


/**
 *  将消息加入本地数组
 *
 *  @return
 */
- (void)appendAndDisplayMessage:(RCMessage *)rcMessage {
    if (!rcMessage) {
        return;
    }
    @try {
        RCDLiveMessageModel *model = [[RCDLiveMessageModel alloc] initWithMessage:rcMessage];
        if([rcMessage.content isMemberOfClass:[RCDLiveGiftMessage class]]){
            model.messageId = -1;
        }
        if ([self appendMessageModel:model]) {
            NSIndexPath *indexPath =
            [NSIndexPath indexPathForItem:self.conversationDataRepository.count - 1
                                inSection:0];
            if ([self.conversationMessageCollectionView numberOfItemsInSection:0] !=
                self.conversationDataRepository.count - 1) {
                return;
            }
            [self.conversationMessageCollectionView
             insertItemsAtIndexPaths:[NSArray arrayWithObject:indexPath]];
            if ([self isAtTheBottomOfTableView] || self.isNeedScrollToButtom) {
                [self scrollToBottomAnimated:YES];
                self.isNeedScrollToButtom=NO;
            }
        }
    } @catch (NSException *e) {
        NSLog(@"ChatRoomView-->appendAndDisplayMessage Exception: %@", e);
    } @finally {
        
    }
}

- (void)sendReceivedDanmaku:(RCMessageContent *)messageContent {
    if([messageContent isMemberOfClass:[RCInformationNotificationMessage class]]){
        RCInformationNotificationMessage *msg = (RCInformationNotificationMessage *)messageContent;
        //        [self sendDanmaku:msg.message];
        [self sendCenterDanmaku:msg.message];
        [self refreshChatRoomMemberCount];
    }else if ([messageContent isMemberOfClass:[RCTextMessage class]]){
        RCTextMessage *msg = (RCTextMessage *)messageContent;
        [self sendDanmaku:msg.content];
    }else if([messageContent isMemberOfClass:[RCDLiveGiftMessage class]]){
        RCDLiveGiftMessage *msg = (RCDLiveGiftMessage *)messageContent;
        NSString *tip = [msg.type isEqualToString:@"0"]?@"送了一个钻戒":@"为主播点了赞";
        NSString *text = [NSString stringWithFormat:@"%@ %@",msg.senderUserInfo.name,tip];
        [self sendDanmaku:text];
    }
}

/**
 *  如果当前会话没有这个消息id，把消息加入本地数组
 *
 *  @return
 */
- (BOOL)appendMessageModel:(RCDLiveMessageModel *)model {
    long newId = model.messageId;
    for (RCDLiveMessageModel *__item in self.conversationDataRepository) {
        /*
         * 当id为－1时，不检查是否重复，直接插入
         * 该场景用于插入临时提示。
         */
        if (newId == -1) {
            break;
        }
        if (newId == __item.messageId) {
            return NO;
        }
    }
    if (!model.content) {
        return NO;
    }
    //这里可以根据消息类型来决定是否显示，如果不希望显示直接return NO
    
    //数量不可能无限制的大，这里限制收到消息过多时，就对显示消息数量进行限制。
    //用户可以手动下拉更多消息，查看更多历史消息。
    if (self.conversationDataRepository.count>100) {
        //                NSRange range = NSMakeRange(0, 1);
        RCDLiveMessageModel *message = self.conversationDataRepository[0];
        [[RCIMClient sharedRCIMClient]deleteMessages:@[@(message.messageId)]];
        [self.conversationDataRepository removeObjectAtIndex:0];
        [self.conversationMessageCollectionView reloadData];
    }
    
    [self.conversationDataRepository addObject:model];
    return YES;
}

/**
 *  UIResponder
 *
 *  @return
 */
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    return [super canPerformAction:action withSender:sender];
}

/**
 *  找出消息的位置
 *
 *  @return
 */
- (NSInteger)findDataIndexFromMessageList:(RCDLiveMessageModel *)model {
    NSInteger index = 0;
    for (int i = 0; i < self.conversationDataRepository.count; i++) {
        RCDLiveMessageModel *msg = (self.conversationDataRepository)[i];
        if (msg.messageId == model.messageId) {
            index = i;
            break;
        }
    }
    return index;
}


/**
 *  打开大图。开发者可以重写，自己下载并且展示图片。默认使用内置controller
 *
 *  @param imageMessageContent 图片消息内容
 */
- (void)presentImagePreviewController:(RCDLiveMessageModel *)model {
}

/**
 *  打开地理位置。开发者可以重写，自己根据经纬度打开地图显示位置。默认使用内置地图
 *
 *  @param locationMessageContent 位置消息
 */
- (void)presentLocationViewController:
(RCLocationMessage *)locationMessageContent {
    
}

/**
 *  关闭提示框
 *
 *  @param theTimer theTimer description
 */
- (void)timerForHideHUD:(NSTimer*)theTimer//弹出框
{
    __weak __typeof(&*self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    });
    [theTimer invalidate];
    theTimer = nil;
}


/*!
 发送消息(除图片消息外的所有消息)
 
 @param messageContent 消息的内容
 @param pushContent    接收方离线时需要显示的远程推送内容
 
 @discussion 当接收方离线并允许远程推送时，会收到远程推送。
 远程推送中包含两部分内容，一是pushContent，用于显示；二是pushData，用于携带不显示的数据。
 
 SDK内置的消息类型，如果您将pushContent置为nil，会使用默认的推送格式进行远程推送。
 自定义类型的消息，需要您自己设置pushContent来定义推送内容，否则将不会进行远程推送。
 
 如果您需要设置发送的pushData，可以使用RCIM的发送消息接口。
 */
- (void)sendMessage:(RCMessageContent *)messageContent
        pushContent:(NSString *)pushContent {
    if (_targetId == nil) {
        return;
    }
    messageContent.senderUserInfo = [RCDLive sharedRCDLive].currentUserInfo;
    if (messageContent == nil) {
        return;
    }
    [[RCDLive sharedRCDLive] sendMessage:self.conversationType
                                targetId:self.targetId
                                 content:messageContent
                             pushContent:pushContent
                                pushData:nil
                                 success:^(long messageId) {
                                     __weak typeof(&*self) __weakself = self;
                                     dispatch_async(dispatch_get_main_queue(), ^{
                                         RCMessage *message = [[RCMessage alloc] initWithType:__weakself.conversationType
                                                                                     targetId:__weakself.targetId
                                                                                    direction:MessageDirection_SEND
                                                                                    messageId:messageId
                                                                                      content:messageContent];
                                         if ([message.content isMemberOfClass:[RCDLiveGiftMessage class]] ) {
                                             message.messageId = -1;//插入消息时如果id是-1不判断是否存在
                                         }
                                         [__weakself appendAndDisplayMessage:message];
                                         [__weakself.inputBar clearInputView];
                                     });
                                 } error:^(RCErrorCode nErrorCode, long messageId) {
                                     [[RCIMClient sharedRCIMClient]deleteMessages:@[ @(messageId) ]];
                                 }];
}

/**
 *  接收到消息的回调
 *
 *  @param notification
 */
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    @try {
        
    __block RCMessage *rcMessage = notification.object;
    RCDLiveMessageModel *model = [[RCDLiveMessageModel alloc] initWithMessage:rcMessage];
    NSDictionary *leftDic = notification.userInfo;
    if (leftDic && [leftDic[@"left"] isEqual:@(0)]) {
        self.isNeedScrollToButtom = YES;
    }
    if (model.conversationType == self.conversationType &&
        [model.targetId isEqual:self.targetId]) {
        __weak typeof(&*self) __blockSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (rcMessage) {
                [__blockSelf appendAndDisplayMessage:rcMessage];
                UIMenuController *menu = [UIMenuController sharedMenuController];
                menu.menuVisible=NO;
                //如果消息不在最底部，收到消息之后不滚动到底部，加到列表中只记录未读数
                if (![self isAtTheBottomOfTableView]) {
                    self.unreadNewMsgCount ++ ;
                    [self updateUnreadMsgCountLabel];
                }
            }
        });
    }
    if([NSThread isMainThread]){
        [self sendReceivedDanmaku:rcMessage.content];
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self sendReceivedDanmaku:rcMessage.content];
        });
    }
        
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  定义展示的UICollectionViewCell的个数
 *
 *  @return
 */
- (void)tap4ResetDefaultBottomBarStatus:
(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        //        CGRect collectionViewRect = self.conversationMessageCollectionView.frame;
        //        collectionViewRect.size.height = self.contentView.bounds.size.height - 0;
        //        [self.conversationMessageCollectionView setFrame:collectionViewRect];
        [self.inputBar setInputBarStatus:RCDLiveBottomBarDefaultStatus];
        self.inputBar.hidden = YES;
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

/**
 *  判断消息是否在collectionView的底部
 *
 *  @return 是否在底部
 */
- (BOOL)isAtTheBottomOfTableView {
    if (self.conversationMessageCollectionView.contentSize.height <= self.conversationMessageCollectionView.frame.size.height) {
        return YES;
    }
    if(self.conversationMessageCollectionView.contentOffset.y +200 >= (self.conversationMessageCollectionView.contentSize.height - self.conversationMessageCollectionView.frame.size.height)) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - 输入框事件
/**
 *  点击键盘回车或者emoji表情面板的发送按钮执行的方法
 *
 *  @param text  输入框的内容
 */
- (void)onTouchSendButton:(NSString *)text{
    RCTextMessage *rcTextMessage = [RCTextMessage messageWithContent:text];
    [self sendMessage:rcTextMessage pushContent:nil];
    [self sendDanmaku:rcTextMessage.content];
    //    [self.inputBar setInputBarStatus:KBottomBarDefaultStatus];
    //    [self.inputBar setHidden:YES];
}

//修复ios7下不断下拉加载历史消息偶尔崩溃的bug
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark RCInputBarControlDelegate

/**
 *  根据inputBar 回调来修改页面布局，inputBar frame 变化会触发这个方法
 *
 *  @param frame    输入框即将占用的大小
 *  @param duration 时间
 *  @param curve
 */
- (void)onInputBarControlContentSizeChanged:(CGRect)frame withAnimationDuration:(CGFloat)duration andAnimationCurve:(UIViewAnimationCurve)curve{
//    CGRect collectionViewRect = self.contentView.frame;
//    self.contentView.backgroundColor = [UIColor clearColor];
//    collectionViewRect.origin.y = self.view.bounds.size.height -frame.size.height- collectionViewRect.size.height+224;
////    collectionViewRect.origin.y = self.playHeight+self.titleHeight+1;
//    
//    collectionViewRect.size.height = self.contentView.bounds.size.height;
//    [UIView animateWithDuration:duration animations:^{
//        [UIView setAnimationCurve:curve];
//        [self.contentView setFrame:collectionViewRect];
//        [UIView commitAnimations];
//    }];
    CGRect inputbarRect = self.inputBar.frame;
    
    inputbarRect.origin.y = self.view.frame.size.height -frame.size.height;
    [self.inputBar setFrame:inputbarRect];
    [self.view bringSubviewToFront:self.inputBar];
    [self scrollToBottomAnimated:NO];
}


- (BOOL)shouldAutorotate{
    return NO;
}

/**
 *  根据inputBar 回调来修改页面布局，inputBar frame 变化会触发这个方法
 *  隐藏
 *  @param frame    输入框即将占用的大小
 *  @param duration 时间
 *  @param curve
 */
- (void)onInputBarControlContentSizeChanged2:(CGRect)frame withAnimationDuration:(CGFloat)duration andAnimationCurve:(UIViewAnimationCurve)curve{
    CGRect inputbarRect = self.inputBar.frame;
    
    inputbarRect.origin.y = self.view.bounds.size.height;
    [self.inputBar setFrame:inputbarRect];
    self.inputBar.hidden = YES;
//    [self.view bringSubviewToFront:self.inputBar];
    [self scrollToBottomAnimated:NO];
}


//- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator{
//    NSLog(@"willTransitionToTraitCollection-------翻转-----------------");
////            CGRect checkPlayRect = self.livePlayingManager.frame;
////            if(checkPlayRect.size.height==self.view.bounds.size.height) {
////                checkPlayRect.size.height = self.playHeight;
////                checkPlayRect.size.width = self.view.bounds.size.width;
////                self.livePlayingManager.frame = checkPlayRect;
////                [self.view addSubview:self.livePlayingManager];
////            }
//    if(self.interfaceOrientation > UIInterfaceOrientationPortrait) {
//        //[self.navigationController popViewControllerAnimated:YES];
//        //[self.delegate restoreView];
//        [self.navigationController popViewControllerAnimated:YES];
//        [self.view addSubview:self.livePlayingManager];
//    }
//}


//
///**
// *  屏幕翻转
// *
// *  @param newCollection <#newCollection description#>
// *  @param coordinator   <#coordinator description#>
// */
//- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator{
//    [super willTransitionToTraitCollection:newCollection
//                 withTransitionCoordinator:coordinator];
//    [coordinator animateAlongsideTransition:^(id <UIViewControllerTransitionCoordinatorContext> context)
//     {
//         if (newCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact) {
//             //To Do: modify something for compact vertical size
//             [self changeCrossOrVerticalscreen:NO];
//         } else {
//             [self changeCrossOrVerticalscreen:YES];
//             //To Do: modify something for other vertical size
//         }
//         [self.view setNeedsLayout];
//     } completion:nil];
//}

/**
 *  横竖屏切换
 *
 *  @param isVertical isVertical description
 */
-(void)changeCrossOrVerticalscreen:(BOOL)isVertical{
    _isScreenVertical = isVertical;
    if (!isVertical) {
        self.livePlayingManager.currentLiveView.frame = self.view.frame;
    } else {
        self.livePlayingManager.currentLiveView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - self.contentView.frame.size.height);
    }
    float inputBarOriginY = self.conversationMessageCollectionView.bounds.size.height + 30;
    float inputBarOriginX = self.conversationMessageCollectionView.frame.origin.x;
    float inputBarSizeWidth = self.contentView.frame.size.width;
    float inputBarSizeHeight = MinHeight_InputView;
    //添加输入框
    [self.inputBar changeInputBarFrame:CGRectMake(inputBarOriginX, inputBarOriginY,inputBarSizeWidth,inputBarSizeHeight)];
    for (RCDLiveMessageModel *__item in self.conversationDataRepository) {
        __item.cellSize = CGSizeZero;
    }
    [self ls_changeModel:YES];
    [self.view bringSubviewToFront:self.backBtn];
    [self.inputBar setHidden:YES];
}

/**
 *  连接状态改变的回调
 *
 *  @param status <#status description#>
 */
- (void)onConnectionStatusChanged:(RCConnectionStatus)status {
    self.currentConnectionStatus = status;
}


- (void)ls_praiseHeart{
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(self.view.frame.size.width-100 , self.view.frame.size.height - 49, 35, 35);
    imageView.image = [UIImage imageNamed:@"heart"];
    imageView.backgroundColor = [UIColor clearColor];
    imageView.clipsToBounds = YES;
    [self.view addSubview:imageView];
    
    
    CGFloat startX = round(random() % 200);
    CGFloat scale = round(random() % 2) + 1.0;
    CGFloat speed = 1 / round(random() % 900) + 0.6;
    int imageName = round(random() % 7);
    NSLog(@"%.2f - %.2f -- %d",startX,scale,imageName);
    
    [UIView beginAnimations:nil context:(__bridge void *_Nullable)(imageView)];
    [UIView setAnimationDuration:7 * speed];
    
    imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"heart%d.png",imageName]];
    imageView.frame = CGRectMake(self.view.frame.size.width-100, -100, 35 * scale, 35 * scale);
//    imageView.frame = CGRectMake(kBounds.width - startX, -100, 35 * scale, 35 * scale);
    
    [UIView setAnimationDidStopSelector:@selector(ls_onAnimationComplete:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}


- (void)ls_praiseGift{
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(self.inputBar.frame.origin.x , self.inputBar.frame.origin.y - 49, 35, 35);
    imageView.image = [UIImage imageNamed:@"gift"];
    imageView.backgroundColor = [UIColor clearColor];
    imageView.clipsToBounds = YES;
    [self.view addSubview:imageView];
    
    
    CGFloat startX = round(random() % 200);
    CGFloat scale = round(random() % 2) + 1.0;
    CGFloat speed = 1 / round(random() % 900) + 0.6;
    int imageName = round(random() % 2);
    NSLog(@"%.2f - %.2f -- %d",startX,scale,imageName);
    
    [UIView beginAnimations:nil context:(__bridge void *_Nullable)(imageView)];
    [UIView setAnimationDuration:7 * speed];
    
    imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"gift%d.png",imageName]];
    imageView.frame = CGRectMake(kBounds.width - startX, -100, 35 * scale, 35 * scale);
    
    [UIView setAnimationDidStopSelector:@selector(ls_onAnimationComplete:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}


- (void)ls_onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    
    UIImageView *imageView = (__bridge UIImageView *)(context);
    [imageView removeFromSuperview];
}


-(void)setupTabTitleView {
    //添加切换页签
    _tabTitleView = [[UIScrollView alloc] init];
    
    _tabTitleView.frame = CGRectMake(0, self.playHeight+self.titleHeight, self.view.bounds.size.width, self.tabHeight);
    _tabTitleView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    _tabTitleView.alpha = 0.5;
    [self.view addSubview:_tabTitleView];
    
    UIView *lineView = [[UILabel alloc] initWithFrame:CGRectMake(0, _tabHeight-1, self.view.bounds.size.width, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [_tabTitleView addSubview:lineView];
    
    [self setupAllTitleButton];
}


#pragma mark - 添加添加所有标题
- (void)setupAllTitleButton
{
    CGFloat btnW = 100;
    CGFloat btnH = _tabTitleView.xmg_height;
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    NSArray *buttonTitleArray = [NSArray arrayWithObjects:@"边看边聊",@"图文详情",@"热门推荐", nil];
    
    for (int i = 0; i < buttonTitleArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        btnX = i * btnW;
        NSString *curtitle = [buttonTitleArray objectAtIndex:i];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        [btn setTitle:curtitle forState:UIControlStateNormal];
        [_tabTitleView addSubview:btn];
        // 颜色
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        // 设置字体
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        
        [btn addTarget:self action:@selector(tabTitleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 0) {
            [self tabTitleClick:btn];
            // 添加下划线
            UIView *underLine = [[UIView alloc] init];
            underLine.backgroundColor = [UIColor redColor];
            [self.tabTitleView addSubview:underLine];
            
            underLine.xmg_height = 3;
            
            underLine.xmg_y = btn.xmg_height - underLine.xmg_height;
            // 一定记得用btn.titleLabel 调用sizeToFit
            [btn.titleLabel sizeToFit];
            // 设置尺寸
            underLine.xmg_width = btn.titleLabel.xmg_width;
            
            // 下划线中心点位置 等于按钮中心点位置
            underLine.xmg_centerX = btn.xmg_centerX;
            
            //            NSLog(@"%@",NSStringFromCGRect(underLine.frame));
            _underLine = underLine;
        }
        [self.buttons addObject:btn];
    }
}


#pragma mark - 选中按钮
- (void)selButton:(UIButton *)button
{
    _selectButton.selected = NO;
    button.selected = YES;
    _selectButton = button;
    
    // 移动下划线
    [UIView animateWithDuration:0.25 animations:^{
        _underLine.xmg_centerX = button.xmg_centerX;
        
    }];
}


// 点击TAB标题按钮就会调用
- (void)tabTitleClick:(UIButton *)button
{
    // 角标
    NSInteger i = button.tag;
    
    // 1.选中按钮
    [self selButton:button];
    if(i==0) {
        self.detailView.hidden = YES;
        self.hotTJTableView.hidden = YES;
        self.contentView.hidden = NO;
    }else if(i==1) {
        self.detailView.hidden = NO;
        self.hotTJTableView.hidden = YES;
        self.contentView.hidden = YES;
    }else if(i==2) {
        self.detailView.hidden = YES;
        self.hotTJTableView.hidden = NO;
        self.contentView.hidden = YES;
    }
//
//    // 2.滚动到对应位置
//    CGFloat offsetX = i * ZWScreenW;
//    self.bottomContainerView.contentOffset = CGPointMake(offsetX, 0);
    
}




#pragma mark tableViewDatasouce Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.hotTJNews count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        M_News *news = [self.hotTJNews objectAtIndex:indexPath.row];
        
        if (self.wohs == 1) {
            //特殊新闻
            NewsOneOfImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsOneOfImageCell"];
            cell.newsData = news;
            return cell;
        }
        if (self.wohs == 2) {
            //问吧
            
            if([news.f_type intValue]==1){
                //问吧专题
                ZhuanTiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZhuanTiCell"];
                cell.newsData = news;
                return cell;
            }else{
                //问吧普通cell
                NewsQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsQuestionCell"];
                cell.newsData = news;
                cell.newsQuestionCellDelegate=self;
                return cell;
            }
            
        }
        
        
        if ([news.f_commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
            //3张图片的新闻
            NewsAdvCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsAdvCell"];
            cell.newsData = news;
            return cell;
        }
        
        if ([news.f_type isEqualToString:@"doc"]) {
            //普通新闻，一张图，标题
            NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
            cell.newsData = news;
            return cell;
        }
        else if([news.f_type isEqualToString:@"slide"]) {
            //3张图片的新闻
            NewsImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsImageCell"];
            cell.newsData = news;
            return cell;
        }
        else {
            //其他，待定
            NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
            cell.newsData = news;
            return cell;
        }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        M_News *news = [self.hotTJNews objectAtIndex:indexPath.row];
        
        
        if (self.wohs == 1||self.wohs == 2) {
            //特殊新闻
            return 251.0f;
        }
        
        if ([news.f_type isEqualToString:@"doc"]) {
            //普通新闻，一张图，标题
            return 100.0f;
        }
        else if([news.f_type isEqualToString:@"slide"]) {
            //3张图片的新闻
            return 155.0f;
        }
        else {
            //其他，待定
            return 0;
        }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    M_News *news_ = [self.hotTJNews objectAtIndex:indexPath.row];
    [self.livePlayingManager pausePlaying];
    [self jumpToNewsDetail:news_];
}

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSString *titileString = [NSString stringWithFormat:@"你点击了按钮%@",[self.hotTJNews objectAtIndex:[indexPath row]]];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"message:titileString delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil];
    [alert show];
    
}

- (void)refreshData
{
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    NSString *subURL=@"http://www3.ctdsb.net/index.php?m=live&c=index&a=postdata";
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doHotNewsList:subURL pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
        [weak_self.hotTJTableView.mj_header endRefreshing];
        NSArray *listNews_ = [responseObject objectForKey:@"list"];
        weak_self.hotTJNews = [NSMutableArray array];
        if (listNews_) {
            [weak_self.hotTJNews addObjectsFromArray:listNews_];
        }
        
        
        [weak_self.hotTJTableView reloadData];
        if ([listNews_ count]<DEFAULT_PAGE_SIZE) {
            [weak_self.hotTJTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [weak_self.mainView sendSubviewToBack:weak_self.hotTJTableView];
        [weak_self.mainView sendSubviewToBack:weak_self.detailView];
        [weak_self.mainView bringSubviewToFront:weak_self.contentView];
    } failure:^(NSString *message) {
        [weak_self.hotTJTableView.mj_header endRefreshing];
    }];
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    NSString *subURL=@"http://www3.ctdsb.net/index.php?m=live&c=index&a=postdata";
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doHotNewsList:subURL pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
        
        [weak_self.hotTJTableView.mj_footer endRefreshing];
        NSArray *listNews_ = [responseObject objectForKey:@"list"];
        if (listNews_) {
            [weak_self.hotTJNews addObjectsFromArray:listNews_];
        }
        
        [weak_self.hotTJTableView reloadData];
        if ([listNews_ count]<DEFAULT_PAGE_SIZE) {
            [weak_self.hotTJTableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSString *message) {
        [weak_self.hotTJTableView.mj_footer endRefreshing];
    }];
}



-(void) toWenBaCtgListPage:(NSString *) ctgUrl{
    //去问吧专题界面
    //专题
    WenBaTagListController *controller = [WenBaTagListController new];
    controller.hidesBottomBarWhenPushed = YES;
    controller.subURL =ctgUrl;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)jumpToNewsDetail:(M_News *)news_
{
    if (self.wohs == 2){
        if([news_.f_type isEqualToString:@"1"]){
            //问吧专题
            [self toWenBaCtgListPage:news_.f_url];
        }else{
            //问吧详情
            WenBaDetailController *controller = [WenBaDetailController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.subURL=news_.f_url;
            if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
                [self showViewController:controller sender:self];
            }else{
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
        
    }else {
        [ServiceNews doSendRead:news_.f_id
                        success:^(id responseObject, NSString *message)
         {}
                        failure:^(NSString *message)
         {}];
        
        //3种跳转方式
        if ([news_.f_type isEqualToString:@"slide"]) {
            //图集
            NewsAlbumViewController *controller = [NewsAlbumViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = news_.f_url;
            controller.f_thumbnail = news_.f_thumbnail;
            if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
                [self showViewController:controller sender:self];
            }else{
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
        else if([news_.f_type isEqualToString:@"doc"]) {
            if ([news_.f_commentsUrl rangeOfString:@"type=forward"].location != NSNotFound) {
                //外链新闻
                NewsWebViewController *controller = [NewsWebViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = news_.f_commentsUrl;
                controller.imgUrlString = news_.f_thumbnail;
                controller.titleString = news_.f_title;
                if ([news_.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
                {
                    controller.hasShare = YES;
                }
                [self.navigationController pushViewController:controller animated:YES];
            }
            else if ([news_.f_commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
                //广告
                NewsWebViewController *controller = [NewsWebViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = news_.f_commentsUrl;
                controller.imgUrlString = news_.f_thumbnail;
                controller.titleString = news_.f_title;
                if ([news_.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
                {
                    controller.hasShare = YES;
                }
                [self.navigationController pushViewController:controller animated:YES];
            }
            else if ([news_.f_commentsUrl rangeOfString:@"type=zt"].location != NSNotFound) {
                //专题链接形式
                NewsWebViewController *controller = [NewsWebViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = news_.f_commentsUrl;
                controller.imgUrlString = news_.f_thumbnail;
                controller.titleString = news_.f_title;
                if ([news_.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
                {
                    controller.hasShare = YES;
                }
                [self.navigationController pushViewController:controller animated:YES];
            }
            else if ([news_.f_commentsUrl rangeOfString:@"specialid="].location != NSNotFound) {
                //专题
                SpecialNewsListViewController *controller = [SpecialNewsListViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.sharethumb=news_.f_thumbnail;
                controller.sharetitle=news_.f_title;
                controller.subURL = [NSString stringWithFormat:@"%@&%@",URL_SUB_GET_SPECIAL_NEWS,[[news_.f_commentsUrl componentsSeparatedByString:@"?"] lastObject]];
                [self.navigationController pushViewController:controller animated:YES];
            }
            else {
//                if(news_.f_id !=nil) {
//                    [self loginRongCloud:nil];
//                }else {
                    //普通新闻详情，需要请求详情，拼接HTML
                    NewsDetailViewController *controller = [NewsDetailViewController new];
                    controller.hidesBottomBarWhenPushed = YES;
                    controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
                    controller.f_thumbnail = news_.f_thumbnail;
                    if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
                        [self showViewController:controller sender:self];
                    }else{
                        [self.navigationController pushViewController:controller animated:YES];
                    }
//                }
            }
        }
        else {
            //待定
        }
    }
    
}

- (void)selectedWord:(NSString *)selword
{
    if(selword==nil) {
        return;
    }
    RCTextMessage *rcTextMessage = [RCTextMessage messageWithContent:selword];
    [self sendMessage:rcTextMessage pushContent:nil];
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

@end

